package com.noble.meether.fragment.mail.store;

import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;

import com.noble.meether.db.utils.CursorUtil;
import com.noble.meether.fragment.mail.bean.UserMessage;

import rx.functions.Func1;

/**
 * 数据库： 消息列表
 */
public class MsgListTable {
    public static final String TABLE_NAME = "messagelist";   // 表名

    // 消息体字段
    public static final String COLUMN_ID = "WhisperID";
    public static final String COLUMN_NAME = "NickName";
    public static final String COLUMN_AVATAR = "Avatar";
    public static final String COLUMN_VIP = "Vip";

    public static final String COLUMN_CONTENT = "Content";
    public static final String COLUMN_TIME = "UpdateTime";

    // 自定义字段
    public static final String ID = "id";                         // 自增id

    // 建表语句
    public static String getCreateTable() {
        return "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
                ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COLUMN_ID + " INT," +
                COLUMN_NAME + " TEXT," +
                COLUMN_AVATAR + " TEXT," +
                COLUMN_VIP + " INT," +
                COLUMN_CONTENT + " TEXT," +
                COLUMN_TIME + " INT);";
    }

    // 根据表中的row生成一个对象
    public static Func1<Cursor, UserMessage> MAPPER = cursor -> {
        UserMessage data = new UserMessage();
        data.setWhisperID(CursorUtil.getInt(cursor, COLUMN_ID));
        data.setNickName(CursorUtil.getString(cursor, COLUMN_NAME));
        data.setAvatar(CursorUtil.getString(cursor, COLUMN_AVATAR));
        data.setVipStatus(CursorUtil.getInt(cursor, COLUMN_VIP));
        data.setContent(CursorUtil.getString(cursor, COLUMN_CONTENT));
        data.setUpdateTime(CursorUtil.getLong(cursor, COLUMN_TIME));
        return data;
    };

    // 根据对象生成一条数据库记录
    public static ContentValues toContentValues(UserMessage data) {
        ContentValues values = new ContentValues();
        if (data.getWhisperID() > 0)
            values.put(COLUMN_ID, data.getWhisperID());
        if (!TextUtils.isEmpty(data.getNickName()))
            values.put(COLUMN_NAME, data.getNickName());
        if (!TextUtils.isEmpty(data.getAvatar()))
            values.put(COLUMN_AVATAR, data.getAvatar());
        values.put(COLUMN_VIP, data.getVipStatus());
        if (!TextUtils.isEmpty(data.getContent()))
            values.put(COLUMN_CONTENT, data.getContent());
        if (data.getUpdateTime() > 0)
            values.put(COLUMN_TIME, data.getUpdateTime());
        return values;
    }

}
